const Types = require('Types');

/**
 * 扑克管理类，用来管理一副或多副牌
 * @param numberOfDecks
 * @constructor
 */
function Decks(numberOfDecks) {
    this._numberOfDecks = numberOfDecks;
    this._cardIds = new Array(numberOfDecks * 52);
    this.reset();
}

/**
 * 重置所有牌
 */
Decks.prototype.reset = function () {
    this._cardIds.length = this._numberOfDecks * 52;
    let index = 0;
    const fromId = Types.Card.fromId;
    for(let i = 0; i < this._numberOfDecks; ++i) {
        for(let cardId = 0; cardId < 52; ++cardId) {
            this._cardIds[index] = fromId(cardId);
            ++index;
        }
    }
}

/**
 * 随机抽一张牌，没有，则返回 null
 * @returns {null|*}
 */
Decks.prototype.draw = function () {
    const cardIds = this._cardIds;
    const len = cardIds.length;
    if (len === 0) {
        return null
    }
    const random = Math.random();
    const index = (random*len) | 0;
    const result = cardIds[index];

    // 去除已经被抽掉的牌
    cardIds[index] = cardIds[len - 1];
    cardIds.length = len-1;
    return result;
}

/**
* 洗牌
* @method shuffle
*/
Decks.prototype.shuffle = function () {
   shuffleArray(this._cardIds);
};

/**
* Randomize array element order in-place.
* Using Durstenfeld shuffle algorithm.
* http://stackoverflow.com/a/12646864
*/

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

module.exports = Decks;